#!/usr/bin/env python
# -*- coding: utf-8 -*-

from math import fabs
import sys
import os
import time
import json
import argparse
from wordpress_publisher_optimized import WordPressPublisher
from getContent import ArticleCrawler

class ArticleCrawlerPublisher:
    def __init__(self):
        """
        初始化爬取和发布器
        """
        self.crawler = ArticleCrawler()
        self.publisher = WordPressPublisher()
        
        # 设置cookies
        # cookies = self.publisher.parse_cookies_from_string(cookie_string)
        # self.publisher.session.cookies.update(cookies)
    
    def crawl_and_publish_single(self, article_url, status='draft', category_id=1, download_images=True, featured_media_id=None, upload_images=True):
        """
        爬取单篇文章并发布
        :param article_url: 文章URL
        :param status: 文章状态 ('draft', 'publish', 'private', etc.)
        :param category_id: 分类ID
        :param download_images: 是否下载图片
        :param featured_media_id: 特色图片ID
        :param upload_images: 是否上传文章中的图片到WordPress
        :return: 发布结果
        """
        print(f"正在爬取文章: {article_url}")
        
        # 爬取文章
        article_data = self.crawler.crawl_article(article_url)
        
        if not article_data:
            return {'success': False, 'error': '爬取文章失败'}
        
        print(f"爬取成功，标题: {article_data['title']}")
        
        # 下载图片（可选）
        if download_images:
            article_data = self.crawler.download_images(article_data, save_dir='downloaded_images')
        
        # 上传文章中的图片到WordPress并替换内容中的图片URL
        if upload_images and article_data.get('images'):
            print("正在上传文章中的图片到WordPress...")
            updated_content = article_data['content']
            uploaded_images = []
            
            for img_path in article_data['images']:
                if os.path.exists(img_path):  # 只上传本地存在的图片
                    upload_result = self.publisher.upload_media(img_path)
                    if upload_result['success']:
                        media_id = upload_result['media_id']
                        uploaded_images.append(media_id)
                        # 获取上传后的图片URL
                        media_url = upload_result['data'].get('source_url', '')
                        if media_url:
                            # 替换内容中的本地路径为WordPress媒体URL
                            updated_content = updated_content.replace(img_path, media_url)
                            print(f"   图片上传成功: {img_path} -> {media_url}")
                    else:
                        print(f"   图片上传失败: {img_path} - {upload_result['error']}")
                        # 保留原始路径
                        uploaded_images.append(None)
                else:
                    # 非本地图片，保留原始URL
                    uploaded_images.append(None)
            
            # 更新文章内容
            article_data['content'] = updated_content
            
            # 如果没有指定特色图片，使用第一张上传成功的图片作为特色图片
            if not featured_media_id and uploaded_images:
                for img_id in uploaded_images:
                    if img_id:  # 找到第一个成功上传的图片ID
                        featured_media_id = img_id
                        print(f"使用第一张上传成功的图片作为特色图片，ID: {featured_media_id}")
                        break
        
        # 发布文章
        print("正在发布文章到WordPress...")
        result = self.publisher.create_article(
            title=article_data['title'],
            content=article_data['content'],
            status=status,
            category_id=category_id,
            featured_media_id=featured_media_id
        )
        
        if result['success']:
            post_id = result['post_id']
            print(f"文章发布成功，ID: {post_id}")
            print(f"编辑链接: {self.publisher.site_url}/wp-admin/post.php?post={post_id}&action=edit")
            
            return {
                'success': True, 
                'post_id': post_id, 
                'title': article_data['title'],
                'url': article_url,
                'edit_link': f"{self.publisher.site_url}/wp-admin/post.php?post={post_id}&action=edit",
                'uploaded_images': uploaded_images if upload_images else []
            }
        else:
            print(f"发布失败: {result['error']}")
            return {'success': False, 'error': result['error']}
    
    def crawl_and_publish_batch(self, base_url, max_pages=5, link_selector=None, page_format=None, 
                               status='draft', category_id=1, download_images=True, delay=2, 
                               featured_media_id=None, upload_images=True):
        """
        批量爬取并发布文章
        :param base_url: 基础URL
        :param max_pages: 最大页数
        :param link_selector: 链接选择器
        :param page_format: 页面格式
        :param status: 文章状态
        :param category_id: 分类ID
        :param download_images: 是否下载图片
        :param delay: 请求间隔（秒）
        :param featured_media_id: 特色图片ID
        :param upload_images: 是否上传文章中的图片到WordPress
        :return: 发布结果列表
        """
        # 获取所有文章URL
        print(f"正在获取文章URL列表，基础URL: {base_url}")
        article_urls = self.crawler.get_article_urls(
            base_url=base_url,
            max_pages=max_pages,
            link_selector=link_selector,
            page_format=page_format
        )
        
        if not article_urls:
            return {'success': False, 'error': '未获取到文章URL'}
        
        print(f"获取到 {len(article_urls)} 个文章URL")
        
        # 批量处理
        results = []
        for i, url in enumerate(article_urls, 1):
            print(f"\n处理第 {i}/{len(article_urls)} 篇文章")
            
            result = self.crawl_and_publish_single(
                article_url=url,
                status=status,
                category_id=category_id,
                download_images=download_images,
                featured_media_id=featured_media_id,
                upload_images=upload_images
            )
            
            results.append(result)
            
            # 添加延时，避免请求过于频繁
            if i < len(article_urls) and delay > 0:
                print(f"等待 {delay} 秒...")
                time.sleep(delay)
        
        # 统计结果
        success_count = sum(1 for r in results if r['success'])
        print(f"\n批量处理完成，成功: {success_count}/{len(results)}")
        
        return results

def main():
    # 配置参数
    parser = argparse.ArgumentParser(description='爬取文章并发布到WordPress')
    parser.add_argument('--mode', choices=['single', 'batch'], default='single', help='运行模式')
    parser.add_argument('--url', help='文章URL（单篇模式）')
    parser.add_argument('--base_url', help='基础URL（批量模式）')
    parser.add_argument('--max_pages', type=int, default=5, help='最大页数（批量模式）')
    parser.add_argument('--link_selector', help='链接选择器（批量模式）')
    parser.add_argument('--page_format', help='页面格式（批量模式）')
    parser.add_argument('--status', default='draft', help='文章状态')
    parser.add_argument('--category_id', type=int, default=1, help='分类ID')
    parser.add_argument('--download_images', action='store_true', help='下载图片')
    parser.add_argument('--no_download_images', dest='download_images', action='store_false', help='不下载图片')
    parser.add_argument('--delay', type=int, default=2, help='请求间隔（秒）')
    parser.add_argument('--site_url', default='https://baikekuai.com', help='WordPress网站URL')
    parser.add_argument('--config', help='配置文件路径')
    
    args = parser.parse_args()
    
    # 从配置文件或命令行获取cookie字符串
    cookie_string = ""
    if args.config and os.path.exists(args.config):
        with open(args.config, 'r', encoding='utf-8') as f:
            config = json.load(f)
            cookie_string = config.get('cookie_string', '')
    elif os.path.exists('configs/config.json'):
        # 默认使用configs/config.json
        with open('configs/config.json', 'r', encoding='utf-8') as f:
            config = json.load(f)
            cookie_string = config.get('cookie_string', '')
    else:
        # 默认cookie字符串（需要用户替换为自己的）
        cookie_string = "wordpress_test_cookie=WP%20Cookie%20check; wordpress_logged_in_6cab87fc114ab2806b437cb159875b8b=jltx3099%7C1761567902%7C3vULHkYwpPnm52NR6T0fnW8SZsbF8ucFju4KEm8jgvi%7C9ef5791e34d54a0f6e95c056cb3bcea3a34253d77abd48d457782df30c7f4288; wp-settings-time-1=1761395437; wp-settings-1=libraryContent%3Dbrowse"
    
    # 初始化爬取和发布器
    crawler_publisher = ArticleCrawlerPublisher(args.site_url, cookie_string)
    
    # 根据模式执行
    if args.mode == 'single':
        if not args.url:
            print("单篇模式需要指定 --url 参数")
            return
        
        result = crawler_publisher.crawl_and_publish_single(
            article_url=args.url,
            status=args.status,
            category_id=args.category_id,
            download_images=args.download_images
        )
        
        if result['success']:
            print(f"文章发布成功: {result['title']}")
            print(f"编辑链接: {result['edit_link']}")
        else:
            print(f"发布失败: {result['error']}")
    
    elif args.mode == 'batch':
        if not args.base_url:
            print("批量模式需要指定 --base_url 参数")
            return
        
        results = crawler_publisher.crawl_and_publish_batch(
            base_url=args.base_url,
            max_pages=args.max_pages,
            link_selector=args.link_selector,
            page_format=args.page_format,
            status=args.status,
            category_id=args.category_id,
            download_images=args.download_images,
            delay=args.delay
        )
        
        # 保存结果
        with open('publish_results.json', 'w', encoding='utf-8') as f:
            json.dump(results, f, ensure_ascii=False, indent=2)
        
        print("结果已保存到 publish_results.json")

if __name__ == "__main__":
    main()